package cn.avalon.basic.controller;

import cn.avalon.basic.dto.SmsCodeDto;
import cn.avalon.basic.exception.BusinessException;
import cn.avalon.basic.service.VerifyCodeService;
import cn.avalon.basic.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 验证码接口类
 * @author: Avalon
 * @date: 2022年08月24日 ： 16:40
 * @version: ver1.0
 * @email 709785494@qq.com
 */
@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private VerifyCodeService verifyCodeService;

    @GetMapping("/image/{key}")
    public AjaxResult image(@PathVariable("key") String key) {
        try {
            //调用业务代码获取图形验证码（base64编码的字符串）
            String base64str = verifyCodeService.image(key);
            //将（base64编码的字符串）响应给前端
            return AjaxResult.me().setResultObj(base64str);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "获取验证码失败");
        }
    }

    /**
     * 获取手机验证码接口
     * @param smsCodeDto
     * @return
     */
    @PostMapping("/smsCode")
    public AjaxResult sendSmsCode(@RequestBody SmsCodeDto smsCodeDto){
        try {
            verifyCodeService.smsCode(smsCodeDto);
            return new AjaxResult();
            // 只要有业务异常都要加
        } catch (BusinessException e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"获取手机验证码失败");
        }
    }

    @PostMapping("/binderSmsCode")
    public AjaxResult binderSmsCode(@RequestBody SmsCodeDto smsCodeDto) {
        try {
            verifyCodeService.binderSmsCode(smsCodeDto);
            return new AjaxResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"获取手机验证码失败");
        }
    }
}
